package com.joker.demo.core.domain.enums;


import java.util.concurrent.TimeUnit;

/**
 * @author : feixiang.li
 * @since : 2025-07-25 14:42
 */
public enum JobTimeUnitEnum {


    /**
     * 毫秒/秒/分钟/小时/天
     */
    MILLISECOND(1, "毫秒"),
    SECOND(2, "秒"),
    MINUTE(3, "分钟"),
    HOUR(4, "小时"),
    DAY(5, "天");

    JobTimeUnitEnum(Integer code, String desc) {
        this.code = code;
        this.desc = desc;
    }

    private final Integer code;
    private final String desc;

    public Integer getCode() {
        return code;
    }

    public String getDesc() {
        return desc;
    }


    /**
     * 统一转换成秒
     *
     * @param timeOut  超时时间
     * @param timeUnit 时间单位
     * @return 秒
     */
    public static Integer getTimeOutToSecond(Integer timeOut, Integer timeUnit) {

        if (timeOut == null || timeUnit == null) {
            return null;
        }
        JobTimeUnitEnum jobTimeUnitEnum = getByCode(timeUnit);
        if (jobTimeUnitEnum == null) {
            return null;
        }
        switch (jobTimeUnitEnum) {
            case MILLISECOND:
                return timeOut / 1000;
            case SECOND:
                return timeOut;
            case MINUTE:
                return timeOut * 60;
            case HOUR:
                return timeOut * 60 * 60;
            case DAY:
                return timeOut * 60 * 60 * 24;
            default:
                return null;
        }
    }


    /**
     * 时间单位转换成TimeUnit
     *
     * @param timeUnit 时间单位
     * @return 时间单位-便于传输
     */
    public static Integer convertToTimeUnit(TimeUnit timeUnit) {
        switch (timeUnit) {
            case MILLISECONDS:
                return MILLISECOND.code;
            case SECONDS:
                return SECOND.code;
            case MINUTES:
                return MINUTE.code;
            case HOURS:
                return HOUR.code;
            case DAYS:
                return DAY.code;
            default:
                return null;
        }
    }


    private static JobTimeUnitEnum getByCode(Integer code) {
        for (JobTimeUnitEnum value : JobTimeUnitEnum.values()) {
            if (value.code.equals(code)) {
                return value;
            }
        }
        return null;
    }
}
